﻿using UnityEngine;
using System.Collections;
using AIClasses;
using TileMapClasses;

namespace GUIElements
{
/// <summary>
/// Calculations and visual button for the end of a turn.
/// This calls the AI movement, population growth and advances the time.
/// </summary>
	public class EndTurn : MonoBehaviour
	{
		private bool visible;
		private int time;
		private Rect endTurnPos;
		private Rect clockPos;
	
		//Public variables
		public GUIStyle WindowStyle;
		public GUIStyle boxStyle;
		public GUIStyle labelStyle;

		/// <summary>
		/// Sets default time 12pm, positions EndTurn button and clock.
		/// </summary>
		void Awake ()
		{
			time = 12;
			visible = true;
			endTurnPos = new Rect (Screen.width - 150, Screen.height - 64, 150, 64);
			clockPos = new Rect (Screen.width / 2 - 150, -128, 300, 256);
		}

		/// <summary>
		/// Draws the end turn and clock. Also handles the button press and advancement of time.
		/// </summary>
		void OnGUI ()
		{
			if (visible) {
				if (GUI.Button (endTurnPos, "End Turn", WindowStyle)) {
					ResourceView.Instance.EndTurnCombine ();
					GrowPopulation ();
					AIManager.Instance.EndTurnMove ();
					time += 6;
					if (time == 24) {
						time = 0;
					}
				}
				GUI.Box (clockPos, "", boxStyle);
				GUI.Label (new Rect (clockPos.x, 0, 150, 32), time.ToString () + ":00", labelStyle);
			}
		}

		/// <summary>
		/// Grows the population for every tile.
		/// </summary>
		private void GrowPopulation ()
		{
			tileManager tileMan = tileManager.Instance;
			for (int i = 0; i < tileMan.AmountOfTiles; i++) {
				if (tileMan [i].Controlled == 1) {
					//TODO: make population growth depend on tile type
					tileMan [i].Population = (int)(tileMan [i].Population * 1.15);
				} else if (tileMan [i].Controlled == 2) {
					tileMan [i].Population = (int)(tileMan [i].Population * 0.5);
				}
			}
		}

		/// <summary>
		/// Gets or sets the time.
		/// </summary>
		/// <value>time.</value>
		public int Time {
			get {
				return time;
			}
			set {
				time = value;
			}
		}
	}
}
